package org.garbagecan.springstudy.dao.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDaoJdbcImpl2 implements UserDao {

	private NamedParameterJdbcTemplate jdbcTemplate;

	public User add(User user) {
		String sql = "insert into user (id, name, password) values (:id, :name, :password)";
		MapSqlParameterSource namedParameters = new MapSqlParameterSource();
		namedParameters.addValue("id", user.getId());
		namedParameters.addValue("name", user.getName());
		namedParameters.addValue("password", user.getPassword());
		jdbcTemplate.update(sql, namedParameters);
		return user;
	}

	public void update(User user) {
		String sql = "update user set name=:name, password=:password where id=:id";
		MapSqlParameterSource namedParameters = new MapSqlParameterSource();
		namedParameters.addValue("id", user.getId());
		namedParameters.addValue("name", user.getName());
		namedParameters.addValue("password", user.getPassword());
		jdbcTemplate.update(sql, namedParameters);
	}

	public void delete(User user) {
		String sql = "delete from user where id=:id";
		SqlParameterSource namedParameter = new MapSqlParameterSource("id", user.getId());
		jdbcTemplate.update(sql, namedParameter);
	}
	
	public User findById(String id) {
		String sql = "select id, name, password from USER where id=:id";
		SqlParameterSource namedParameter = new MapSqlParameterSource("id", id);
		RowMapper mapper = new RowMapper() {
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setId(rs.getString("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				return user;
			}
		};
		return (User)jdbcTemplate.queryForObject(sql, namedParameter, mapper);
	}

	public List<User> list() {
		String sql = "select id, name, password from USER";
		RowMapper mapper = new RowMapper() {
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setId(rs.getString("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				return user;
			}
		};
		List<User> users = jdbcTemplate.query(sql, new MapSqlParameterSource(), mapper);
		return users;
	}

	public void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
}
